package com.lsz.crm.interceptor;

/**
 * @Author liushizhong
 * @Date 2021/10/9 20:41
 * @Version 1.0
 */

import com.lsz.crm.exceptions.NoLoginException;
import com.lsz.crm.mapper.UserMapper;
import com.lsz.crm.service.UserService;
import com.lsz.crm.utils.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 非法访问拦截
 *  实现接口 HandlerInterceptor
 */

public class NoLoginInterceptor implements HandlerInterceptor {


    @Autowired
    private UserMapper userMapper;

    /**
     * 拦截用户是否登录
     * 在目标方法执行前，执行这个方法
     * 返回 true 目标方法可以执行，否则不可执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 从 cookie 中获取 userId
        Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);

        // 判断用户是否存在
        if(null == userId || userMapper.selectByPrimaryKey(userId) == null){
            // 抛出登录异常
            throw  new NoLoginException();
        }
        return true;
    }
}
